export function hexify(color) {
  var values = color
    .replace(/rgba?\(/, '')
    .replace(/\)/, '')
    .replace(/[\s+]/g, '')
    .split(',')
  var a = parseFloat(values[3] || 1),
    r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
    g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
    b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
  return (
    '#' +
    ('0' + r.toString(16)).slice(-2) +
    ('0' + g.toString(16)).slice(-2) +
    ('0' + b.toString(16)).slice(-2)
  )
}

export function colorRGBtoHex(color) {
  var rgb = color.split(',')
  var r = parseInt(rgb[0].split('(')[1])
  var g = parseInt(rgb[1])
  var b = parseInt(rgb[2].split(')')[0])
  var hex = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
  return hex
}

export function hslToHex(hsl, bg) {
  function checkHex(v) {
    return 1 === v.length ? '0' + v : v
  }
  var data,
    r,
    g,
    b,
    a,
    cnv = document.createElement('canvas'),
    ctx = cnv.getContext('2d'),
    alpha = /a\(/.test(hsl),
    output = {}

  return (
    (cnv.width = cnv.height = 1),
    bg && ((ctx.fillStyle = bg), ctx.fillRect(0, 0, 1, 1)),
    (ctx.fillStyle = hsl),
    ctx.fillRect(0, 0, 1, 1),
    (data = ctx.getImageData(0, 0, 1, 1).data),
    (r = data[0]),
    (g = data[1]),
    (b = data[2]),
    (a = (data[3] / 255).toFixed(2)),
    alpha
      ? ((output.hsla = hsl),
        bg
          ? (output.rgb = 'rgb(' + r + ',' + g + ',' + b + ')')
          : (output.rgba = 'rgb(' + r + ',' + g + ',' + b + ',' + a + ')'))
      : ((output.hsl = hsl),
        (output.rgb = 'rgb(' + r + ',' + g + ',' + b + ')')),
    (output.hex =
      '#' +
      checkHex(r.toString(16)) +
      checkHex(g.toString(16)) +
      checkHex(b.toString(16))),
    output.hex
  )
}
